package cn.oldfeel.spark.base;

import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 适配器的抽象类
 * 
 * @author oldfeel
 */
public abstract class BaseBaseAdapter extends BaseAdapter {
	protected DisplayImageOptions options;
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	protected LayoutInflater inflater;
	protected Context context;
	private List<Object> list = new LinkedList<Object>();
	/** 适配器中元素的类 */
	private Class<?> classItem;

	/**
	 * 
	 * @param context
	 * @param classItem
	 *            适配器中元素的类
	 */
	public BaseBaseAdapter(Context context, Class<?> class1) {
		this(context, class1, -1);
	}

	/**
	 * 
	 * @param context
	 * @param classItem
	 *            适配器中元素的类
	 * @param id
	 *            默认图片id
	 */
	public BaseBaseAdapter(Context context, Class<?> classItem, int id) {
		this.context = context;
		this.classItem = classItem;
		this.inflater = LayoutInflater.from(context);
		if (id > 0)
			options = new DisplayImageOptions.Builder().showStubImage(id)
					.showImageForEmptyUri(id).showImageOnFail(id)
					.cacheInMemory(true).cacheOnDisc(true)
					/* .displayer(new RoundedBitmapDisplayer(20)) */.build();
	}

	/**
	 * 预处理清除列表数据和获取jsonarray
	 * 
	 * @param page
	 *            页码
	 * @param json
	 *            json对象
	 * @throws JSONException
	 */
	public void putJSON(JSONObject json, int page) {
		if (page == 1) {
			list.clear();
		}
		try {
			JSONArray array = json.getJSONArray("itemList");
			for (int i = 0; i < array.length(); i++) {
				try {
					Object t = classItem.getConstructors()[0].newInstance(array
							.getJSONObject(i));
					addItem(t);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
	}

	/**
	 * 清除list
	 */
	public void clear() {
		list.clear();
		notifyDataSetChanged();
	}

	/**
	 * 添加元素
	 * 
	 * @param t
	 */
	public void addItem(Object t) {
		list.add(t);
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		return getExView(position, convertView, parent);
	}

	public abstract View getExView(int position, View convertView,
			ViewGroup parent);

}
